//
//  NewHomeViewController.m
//  UHealth
//
//  Created by liliang on 15/2/3.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "NewHomeViewController.h"
#import "UserVC.h"
#import "BLEVC.h"
#import "ThermometerView.h"
//#import "ChartV.h"
#import "BlueToothManager.h"
#import "DBManage.h"
#import "NSString+BloodSugar.h"
#import "ChartView.h"
#import "Masonry.h"
#import "SSCheckBoxView.h"
#import "MBProgressHUD+YCL.h"
#import "NewReportV.h"
#import "ServiceVC.h"
#import "LogVC.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>


@interface NewHomeViewController ()<CDRTranslucentSideBarDelegate,UIScrollViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>

@property (weak, nonatomic) IBOutlet UILabel            *currentTemperatureLabel;
@property (weak, nonatomic) IBOutlet UILabel            *highTemperatureLabel;
@property (weak, nonatomic) IBOutlet UILabel            *lowTemperatureLabel;
@property (weak, nonatomic) IBOutlet UIView             *thermometerView;
@property (weak, nonatomic) IBOutlet UILabel            *hintLabel;
@property (weak, nonatomic) IBOutlet UIView             *chartBgView;
//@property (weak, nonatomic) IBOutlet UIScrollView       *bgScrollView;
@property (weak, nonatomic) IBOutlet UIImageView        *editIconImageView;
@property (weak, nonatomic) IBOutlet UILabel            *alertMessageLabel;
@property (weak, nonatomic) IBOutlet UILabel            *monitorInfoLabel;
@property (weak, nonatomic) IBOutlet UIView             *topDataView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hintLabelBottomSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hintLabelTopSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *currentTemperatureTopSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *chartViewHeightConstraint;

@property (nonatomic, strong) ThermometerView           *theThermometerView;
//@property (nonatomic, strong) ChartV                    *chartView;
@property (nonatomic, strong) ChartView                 *chartView;
@property (nonatomic, strong) UserVC                    *leftU;
@property (nonatomic, strong) BLEVC                     *rightB;

@property (nonatomic, strong) UIControl                 *bgCtl;

@property (nonatomic, strong) NSMutableArray            *periArr;
@property (nonatomic, strong) CBCentralManager          *manager;
@property (nonatomic, strong) NSString                  *currentSelectedDeviceId;
@property (nonatomic, strong) NSTimer                   *timer;
@property (nonatomic, strong) UIButton                  *backBtn;
@property (nonatomic, strong) UIView                    *popView;
@property (nonatomic, strong) UIView                    *darkView;
@property (nonatomic, strong) NewReportV                *reportView;
@property (nonatomic, strong) UILabel                   *label1;
@property (nonatomic, strong) UIImageView               *imageView4;
@property (nonatomic, strong) SSCheckBoxView            *check1;
@property (nonatomic, strong) SSCheckBoxView            *check2;
@property (nonatomic, strong) SSCheckBoxView            *check3;
@property (nonatomic, strong) SSCheckBoxView            *check4;


@property (nonatomic)         float                      highestTemperatureValue;
@property (nonatomic)         float                      lowestTemperatureValue;
@property (nonatomic)         float                      shouldShowAlertMessageTemperatureValue;

@end

@implementation NewHomeViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.title = kLocal(@"UHealth");
        self.tabBarItem.image         = [UIImage imageNamed:@"bloodsugar_grey"];
        self.tabBarItem.selectedImage = [UIImage imageNamed:@"bloodsugar_blue"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIBarButtonItem *leftBarBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"burger"] style:UIBarButtonItemStyleBordered target:self action:@selector(leftBarBtnClicked)];
    self.navigationItem.leftBarButtonItem = leftBarBtn;
    
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"bluetooth"] style:UIBarButtonItemStyleBordered target:self action:@selector(rightBarBtnClicked)];
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
    //选择器
    NSArray *segArray = [[NSArray alloc]initWithObjects:kLocal(@"now_tem"),kLocal(@"read_report"),nil];//
    UISegmentedControl *homeSeg = [[UISegmentedControl alloc]initWithItems:segArray];
    homeSeg.layer.masksToBounds = YES;
    homeSeg.frame = CGRectMake(55,25,WIDTH-110, 30);
    homeSeg.selectedSegmentIndex = 0;
    homeSeg.backgroundColor = [UIColor clearColor];
    homeSeg.tintColor = [UIColor colorWithRed:46/255.0f green:166/255.0f blue:222/255.0f alpha:1.0];
    [homeSeg setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    [homeSeg setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    [homeSeg addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];  //添加委托方法
    [self.navigationItem setTitleView:homeSeg];
    
    self.reportView = [[NewReportV alloc]initWithFrame:CGRectMake(0, kNavHeight, self.navigationController.view.frame.size.width, HEIGHT-kTabBarHeight)];
    [self.navigationController.view addSubview:self.reportView];
    [self.reportView.serviceBtn addTarget:self action:@selector(serviceBtnPress) forControlEvents:UIControlEventTouchUpInside];
    self.reportView.hidden = YES;
    
    
    //日志按钮
    UIButton *logBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    logBtn.frame = CGRectMake(self.navigationController.view.frame.size.width - 50, 100, 30, 30);
    logBtn.layer.masksToBounds = YES;
    logBtn.layer.cornerRadius  = 5.0;
    [logBtn setBackgroundImage:[UIImage imageNamed:@"electricity"] forState:UIControlStateNormal];
    [logBtn addTarget:self action:@selector(logbtnPress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:logBtn];
    
    UIButton *setBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect setBtnFrame;
    if (VIEW_3_5_INCH) {
        setBtnFrame = CGRectMake(self.navigationController.view.frame.size.width - 50, logBtn.frame.origin.y+logBtn.frame.size.height+70, 40, 30);
        setBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    }else if (VIEW_4_INCH){
        setBtnFrame = CGRectMake(self.navigationController.view.frame.size.width - 50, logBtn.frame.origin.y+logBtn.frame.size.height+80, 40, 30);
        setBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    }else if (VIEW_4_7_INCH){
        setBtnFrame = CGRectMake(self.navigationController.view.frame.size.width - 50, logBtn.frame.origin.y+logBtn.frame.size.height+130, 40, 30);
        setBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    }else if (VIEW_5_5_INCH){
        setBtnFrame = CGRectMake(self.navigationController.view.frame.size.width - 50, logBtn.frame.origin.y+logBtn.frame.size.height+150, 40, 30);
        setBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    }
    
    setBtn.frame = setBtnFrame;
    setBtn.layer.masksToBounds = YES;
    setBtn.layer.cornerRadius  = 5.0;
    [setBtn setTitle:kLocal(@"setting") forState:UIControlStateNormal];
//    [setBtn setBackgroundImage:[UIImage imageNamed:@"electricity"] forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(setBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:setBtn];
    
//    UIView *darkView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
////    darkView.backgroundColor = [UIColor colorWithRed:171 green:156 blue:147 alpha:0.5];
//    darkView.backgroundColor = [UIColor blueColor];
//    darkView.alpha = 0.5;
//    darkView.hidden = YES;
//    self.darkView = darkView;
//    [self.view addSubview:darkView];

    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.backgroundColor = [UIColor colorWithRed:117.0/255.0 green:117.0/255.0 blue:117.0/255.0 alpha:0.8f];
    backBtn.frame = CGRectMake(0, 0, self.navigationController.view.frame.size.width, HEIGHT);
    [backBtn addTarget:self action:@selector(backbtn) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.view addSubview:backBtn];
    backBtn.hidden = YES;
    self.backBtn = backBtn;
    
    UIView * popView = [[UIView alloc]initWithFrame:CGRectMake(15, kScreenHeight/2-75, self.navigationController.view.frame.size.width-30, 150)];
    popView.backgroundColor = [UIColor whiteColor];
    popView.layer.cornerRadius = 10.0;
    [self.backBtn addSubview:popView];
    self.popView = popView;
    
    UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(10, 13, 15, 15)];
    imageView1.image = [UIImage imageNamed:@"alarm_clock.png"];
    [self.popView addSubview:imageView1];
    
    UILabel * label1 = [[UILabel alloc]initWithFrame:CGRectMake(imageView1.frame.origin.x+imageView1.frame.size.width+5, 10, 160, 20)];
    label1.backgroundColor = [UIColor clearColor];
    label1.font = [UIFont systemFontOfSize:14];
    [self.popView addSubview:label1];
    self.label1 = label1;
    
    UIImageView *imageView4 = [[UIImageView alloc]initWithFrame:CGRectMake(label1.frame.origin.x+label1.frame.size.width+5, imageView1.frame.origin.y, 15, 15)];
    imageView4.image = [UIImage imageNamed:@"edit_pen.png"];
    imageView4.userInteractionEnabled = YES;
    [self.popView addSubview:imageView4];
    self.imageView4 = imageView4;
    
    // 高温警告
    SSCheckBoxView * check1 = [[SSCheckBoxView alloc]initWithFrame:CGRectMake(self.popView.frame.size.width-40, 2, 20, 20) style:kSSCheckBoxViewStyleGlossy checked:YES];
    [self.popView addSubview:check1];
    self.check1 = check1;
    
    
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(label1.frame.origin.x, label1.frame.origin.y+label1.frame.size.height+10, 230, 20)];
    label2.text = kLocal(@"bluetooth_disconnect_warning");
    label2.font = [UIFont systemFontOfSize:14];
    [self.popView addSubview:label2];
    
    UIImageView *imageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(imageView1.frame.origin.x, label2.frame.origin.y+3, 15, 15)];
    imageView2.image = [UIImage imageNamed:@"pic_bluetooth.png"];
    [self.popView addSubview:imageView2];
    
    // 连接状态提醒
    SSCheckBoxView * check2 = [[SSCheckBoxView alloc]initWithFrame:CGRectMake(check1.frame.origin.x, label2.frame.origin.y-8, 20, 20) style:kSSCheckBoxViewStyleGlossy checked:YES];
    [self.popView addSubview:check2];
    self.check2 = check2;
    
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(label1.frame.origin.x, label2.frame.origin.y+label2.frame.size.height+10, 100, 20)];
    label3.text = kLocal(@"remind_mode");
    label3.font = [UIFont systemFontOfSize:14];
    [self.popView addSubview:label3];
    
    UIImageView *imageView3 = [[UIImageView alloc]initWithFrame:CGRectMake(imageView1.frame.origin.x, label3.frame.origin.y+3, 15, 15)];
    imageView3.image = [UIImage imageNamed:@"pic_remind.png"];
    [self.popView addSubview:imageView3];
    
    
    SSCheckBoxView * check3 = [[SSCheckBoxView alloc]initWithFrame:CGRectMake(label3.frame.origin.x+label3.frame.size.width+5, label3.frame.origin.y-8, 60, 20) style:kSSCheckBoxViewStyleGlossy checked:YES];
    [check3 setText:kLocal(@"ring")];
    [self.popView addSubview:check3];
    self.check3 = check3;
    
    SSCheckBoxView * check4 = [[SSCheckBoxView alloc]initWithFrame:CGRectMake(check3.frame.origin.x+check3.frame.size.width+10, label3.frame.origin.y-8, 60, 20) style:kSSCheckBoxViewStyleGlossy checked:YES];
    [check4 setText:kLocal(@"leap_screen")];
    [self.popView addSubview:check4];
    self.check4 = check4;
    
    CGFloat buttonWidth;
    if (VIEW_3_5_INCH) {
        buttonWidth = 30;
    }else if (VIEW_4_INCH){
        buttonWidth = 35;
    }else if (VIEW_4_7_INCH){
        buttonWidth = 40;
    }else if (VIEW_5_5_INCH){
        buttonWidth = 40;
    }
    UIButton *cancelbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelbutton.frame = CGRectMake(40, label3.frame.origin.y+label3.frame.size.height+10, self.popView.frame.size.width-80, buttonWidth);
    [cancelbutton setTitle:kLocal(@"sure") forState:UIControlStateNormal];
    [cancelbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelbutton.layer setMasksToBounds:YES];
    [cancelbutton.layer setCornerRadius:1.0];
    cancelbutton.backgroundColor = kBlueColor;
    [cancelbutton addTarget:self action:@selector(cancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.popView addSubview:cancelbutton];
    
    //温度计界面
//    self.theThermometerView = [[ThermometerView alloc] initWithFrame:self.thermometerView.bounds];
    self.theThermometerView = [[ThermometerView alloc] init];
    [self.thermometerView addSubview:self.theThermometerView];
    UIEdgeInsets padding = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.theThermometerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.thermometerView.mas_top).with.offset(padding.top); //with is an optional semantic filler
        make.left.equalTo(self.thermometerView.mas_left).with.offset(padding.left);
        make.bottom.equalTo(self.thermometerView.mas_bottom).with.offset(-padding.bottom);
        make.right.equalTo(self.thermometerView.mas_right).with.offset(-padding.right);
    }];
    [self.theThermometerView setCurrentTemperature:35.5];
    
//    self.chartView = [[ChartV alloc] initWithFrame:self.chartBgView.bounds];
    
    self.hintLabel.preferredMaxLayoutWidth = self.view.bounds.size.width-32;
    self.hintLabel.text = kLocal(@"continue_hightem");
    
    [self initData];
    [self setUpAlertLabel];

//    self.bgScrollView.scrollEnabled = NO;
    
    // 第一次先刷新一下数据
    [self performSelector:@selector(refreshViewWithHighAndLowTemperatureView) withObject:nil afterDelay:1];
    [self performSelector:@selector(refreshChartView) withObject:nil afterDelay:1];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editAlertViewTapped)];
    [self.imageView4 addGestureRecognizer:tap];

    [self updateViews];
    

}


#pragma mark 选择器
-(void)segmentAction:(UISegmentedControl *)Seg{
    
    NSInteger Index = Seg.selectedSegmentIndex;
    
    switch (Index) {
        case 0:{
            self.view.hidden = NO;
            self.reportView.hidden = YES;

        }
            break;
        case 1:{
            self.view.hidden = YES;
            self.reportView.hidden = NO;
        
        }
            break;
    }
}

-(void)serviceBtnPress{
    [self.tabBarController setSelectedIndex:3];
}

-(void)setBtn{
    self.backBtn.hidden = NO;
    
    self.backBtn.transform = CGAffineTransformMakeScale(1.3, 1.3);
    self.backBtn.alpha = 0;
    [UIView animateWithDuration:.35 animations:^{
        self.backBtn.alpha = 1.0;
        self.backBtn.transform = CGAffineTransformMakeScale(1, 1);
    }];
    
}

-(void)backbtn{
    
    [UIView animateWithDuration:.35 animations:^{
        self.backBtn.transform = CGAffineTransformMakeScale(1.3, 1.3);
        self.backBtn.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            self.backBtn.hidden = YES;
            
        }
    }];
    
}

-(void)cancelBtn{
    [self backbtn];
}

// 显示日志
-(void)logbtnPress{
    
    LogVC *logVC = [[LogVC alloc]init];
    [self presentViewController:logVC animated:YES completion:nil];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self invalidTimer];
//    self.timer = [NSTimer timerWithTimeInterval:30 target:self selector:@selector(refreshChartView) userInfo:nil repeats:YES];
//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self invalidTimer];
}

- (void)invalidTimer
{
    if (self.timer) {
        if ([self.timer isValid]) {
            [self.timer invalidate];
        }
        self.timer = nil;
    }
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
}

- (void)updateViews
{
    if (VIEW_3_5_INCH || VIEW_AT_IPAD || VIEW_AT_IPAD_RETINA_DISPLAY) {
        self.currentTemperatureLabel.font            = [UIFont systemFontOfSize:35];
        self.monitorInfoLabel.font                   = [UIFont systemFontOfSize:11];
        self.hintLabelTopSpaceConstraint.constant    = 0;
        self.hintLabelBottomSpaceConstraint.constant = 0;
        self.hintLabel.font = [UIFont systemFontOfSize:11];
        self.currentTemperatureTopSpaceConstraint.constant = 10;
        self.chartViewHeightConstraint.constant = 150;
    }
    else if (VIEW_4_INCH) {
        self.currentTemperatureLabel.font            = [UIFont systemFontOfSize:50];
        self.monitorInfoLabel.font                   = [UIFont systemFontOfSize:15];
        self.hintLabelTopSpaceConstraint.constant    = 1;
        self.hintLabelBottomSpaceConstraint.constant = 1;
        self.hintLabel.font = [UIFont systemFontOfSize:11];
        self.currentTemperatureTopSpaceConstraint.constant = 15;
        self.chartViewHeightConstraint.constant = 150;
    }
    else if (VIEW_4_7_INCH) {
        self.currentTemperatureLabel.font            = [UIFont systemFontOfSize:72];
        self.monitorInfoLabel.font                   = [UIFont systemFontOfSize:17];
        self.hintLabelTopSpaceConstraint.constant    = 16;
        self.hintLabelBottomSpaceConstraint.constant = 16;
        self.hintLabel.font = [UIFont systemFontOfSize:13];
        self.currentTemperatureTopSpaceConstraint.constant = 20;
        self.chartViewHeightConstraint.constant = 180;
    }
    else if (VIEW_5_5_INCH) {
        self.currentTemperatureLabel.font            = [UIFont systemFontOfSize:80];
        self.monitorInfoLabel.font                   = [UIFont systemFontOfSize:20];
        self.hintLabelTopSpaceConstraint.constant    = 16;
        self.hintLabelBottomSpaceConstraint.constant = 16;
        self.hintLabel.font = [UIFont systemFontOfSize:14];
        self.currentTemperatureTopSpaceConstraint.constant = 30;
        self.chartViewHeightConstraint.constant = 250;
    }
    if (!self.chartView) {
        self.chartView = [[ChartView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, self.chartViewHeightConstraint.constant) dataArray:nil];
        
        [self.chartBgView addSubview:self.chartView];
    }
    [UIView animateWithDuration:0.5 animations:^{
        [self.view updateConstraintsIfNeeded];
        [self.view setNeedsUpdateConstraints];
        [self.view layoutIfNeeded];
        [self.view setNeedsLayout];
    }];
}

- (void)setUpAlertLabel
{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.shouldShowAlertMessageTemperatureValue = [userDefault floatForKey:@"ShouldShowAlertMessageTemperatureValue"];
    if (self.shouldShowAlertMessageTemperatureValue > -0.000001 && self.shouldShowAlertMessageTemperatureValue < 0.000001) {
        self.shouldShowAlertMessageTemperatureValue = 38.5;
        [userDefault setFloat:self.shouldShowAlertMessageTemperatureValue forKey:@"ShouldShowAlertMessageTemperatureValue"];
        [userDefault synchronize];
    }
    NSString *alertStr = [NSString stringWithFormat:@"%@ %.1f℃, %@",kLocal(@"above_tem"),self.shouldShowAlertMessageTemperatureValue,kLocal(@"remind_me")];
    NSRange location = [alertStr rangeOfString:[NSString stringWithFormat:@"%.1f℃",self.shouldShowAlertMessageTemperatureValue]];
    
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:alertStr];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[[UIColor blackColor] colorWithAlphaComponent:0.8]
                          range:NSMakeRange(0, location.location)];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[UIColor colorWithRed:62/255.0 green:180/255.0 blue:234/255.0 alpha:1.0]
                          range:NSMakeRange(location.location, location.length)];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[[UIColor blackColor] colorWithAlphaComponent:0.8]
                          range:NSMakeRange(location.location+location.length, attributedStr.length-(location.location+location.length))];
    self.label1.attributedText = attributedStr;
    
    
}

// 获取当天全部温度数据
- (NSArray *)getCurrentDayAllData
{
    
    // 默认用户
    UserObj *user = [[DBManage sharedManager] getDefUser];
    
    NSString *dayStartStr = [NSString stringWithFormat:@"%@ 00:00:00",[[NSString stringFromDate:[NSDate date]] substringToIndex:10]];
    NSString *dayEndStr = [NSString stringWithFormat:@"%@ 00:00:00",[[NSString stringFromDate:[NSDate dateWithTimeInterval:(24*3600) sinceDate:[NSDate date]]] substringToIndex:10]];
//
    #warning 数据需要筛选，待完善
    NSString *conditionStr = [NSString stringWithFormat:@"UserName = '%@' and MeasureDate > datetime('%@') and MeasureDate < datetime('%@');",user.name,dayStartStr,dayEndStr];
    
    NSArray *dataArray = [[DBManage sharedManager] queryDataFromTable:kTemperatureTable andConditions:conditionStr];
    
    return dataArray;
}


// 刷新最值温度
- (void)refreshViewWithHighAndLowTemperatureView
{
//    kDebug(@"刷新最值温度");
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray *array = [self getCurrentDayAllData];
        
        // 更新最值温度
        for (BodyTemperatureObj *temperatureObj in array) {
            float temperatureValue = temperatureObj.bodyTemperatureValue;
            if (temperatureValue > self.highestTemperatureValue) {
                self.highestTemperatureValue = temperatureValue;
            }
            if (temperatureValue < self.lowestTemperatureValue) {
                self.lowestTemperatureValue = temperatureValue;
            }
        }
        
        // 回到主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            self.highTemperatureLabel.text    = [NSString stringWithFormat:@"%.1f℃",self.highestTemperatureValue];
            self.lowTemperatureLabel.text     = [NSString stringWithFormat:@"%.1f℃",self.lowestTemperatureValue];
            
            // 更新UI
//            NSLog(@"=====================  刷新最值温度");
            [self.view updateConstraintsIfNeeded];
            [self.view layoutIfNeeded];
            
            // 刷新温度曲线
            [self refreshChartView];
        });
    });
}


- (void)PostAlertNotification
{
    UILocalNotification *noti = [[UILocalNotification alloc] init];
    if (noti) {
        //设置推送时间
        noti.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
        //设置时区
        noti.timeZone = [NSTimeZone defaultTimeZone];
        //设置重复间隔
        noti.repeatInterval = 0;
        //推送声音
        noti.soundName = @"alert.mp3";
        NSString* soundPath = [[NSBundle mainBundle] pathForResource:@"alert" ofType:@"mp3"];
        NSLog(@"soundPath:%@", soundPath);
        //内容
        noti.alertBody = kLocal(@"pay_attention");
        //显示在icon上的红色圈中的数子
        noti.applicationIconBadgeNumber = 1;
        //设置userinfo 方便在之后需要撤销的时候使用
        NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
        noti.userInfo = infoDic;
        //添加推送到uiapplication
        UIApplication *app = [UIApplication sharedApplication];
        [app scheduleLocalNotification:noti];
    }
}

// 更新温度曲线
- (void)refreshChartView
{
    NSArray *array = [self getCurrentDayAllData];
    [self.chartView refreshViewWithDataArray:array];
    
//    kDebug(@"刷新曲线");
}

- (void)refreshViewWithCurrentTemperatureValue:(float)temperatureValue
{
    if(self.highestTemperatureValue > -0.000001 && self.highestTemperatureValue < 0.000001) {
        self.highestTemperatureValue = temperatureValue;
    }
    if(self.lowestTemperatureValue > -0.000001 && self.lowestTemperatureValue < 0.000001) {
        self.lowestTemperatureValue = temperatureValue;
    }
    
    if (temperatureValue > self.highestTemperatureValue) {
        self.highestTemperatureValue = temperatureValue;
    }
    if (temperatureValue < self.lowestTemperatureValue) {
        self.lowestTemperatureValue = temperatureValue;
    }
    self.currentTemperatureLabel.text = [NSString stringWithFormat:@"%.1f℃",temperatureValue];
    [self.theThermometerView setCurrentTemperature:temperatureValue];
    self.highTemperatureLabel.text    = [NSString stringWithFormat:@"%.1f℃",self.highestTemperatureValue];
    self.lowTemperatureLabel.text     = [NSString stringWithFormat:@"%.1f℃",self.lowestTemperatureValue];
    
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
    
    if (temperatureValue >= self.shouldShowAlertMessageTemperatureValue) {
        [self PostAlertNotification];
    }
}

- (void)leftBarBtnClicked
{
    [self.leftU show];
}

- (void)rightBarBtnClicked
{
    [self.rightB show];
}

- (void)initData
{
//    self.manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
    self.periArr = [NSMutableArray array];
    
    self.leftU = [[UserVC alloc]init];
    self.leftU.sideBarWidth = 200;
    self.leftU.delegate = self;
    self.leftU.translucentStyle = UIBarStyleBlackTranslucent;
    self.leftU.tag = 0;
    
    // Create Right SideBar
    self.rightB = [[BLEVC alloc] initWithDirection:YES];
    self.rightB.sideBarWidth = 200;
    self.rightB.delegate = self;
    self.rightB.translucentStyle = UIBarStyleBlack;
    self.rightB.tag = 1;
    
    
    __weak __typeof(self) weakSelf = self;
    self.rightB.updateBlock = ^(float temperatureValue, NSInteger contactState){//体温值，连接状态
        
        // 刷新温度显示
        [weakSelf refreshViewWithCurrentTemperatureValue:temperatureValue];
        // 刷新数据显示
        [weakSelf refreshViewWithHighAndLowTemperatureView];

        // 是否高温警告
        if (weakSelf.check1.enabled) {
            if (temperatureValue > weakSelf.shouldShowAlertMessageTemperatureValue) {
                kDebug(@"测试温度: %.1f, 警告温度: %.1f", temperatureValue, weakSelf.shouldShowAlertMessageTemperatureValue);
                [weakSelf PostAlertNotification];
                
                // 警告音
                if (weakSelf.check3.enabled) {
                    [weakSelf playAudio];
                }
                // 弹窗
                if (weakSelf.check4.enabled) {
                    [MBProgressHUD showError:kLocal(@"high_tem")];
                }
            }
        }
        
        // 是否接触状态警告
        if (weakSelf.check2.enabled) {
            if (contactState != 0) {

                // 警告
                if (weakSelf.check3.enabled) {
                    [weakSelf playAudio];
                }
                
                // 弹窗
                if (weakSelf.check4.enabled) {
                    [MBProgressHUD showError:kLocal(@"no_touch")];
                }
            }
        }
  
    };
    // Add PanGesture to Show SideBar by PanGesture
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [self.topDataView addGestureRecognizer:panGestureRecognizer];
}

// 保存日志
- (void)insertLogDataWithType:(int)type {
    
    // 默认用户
    UserObj *user = [[DBManage sharedManager] getDefUser];
    
    // 存储日志
    LogDataObj *log = [[LogDataObj alloc]init];
    log.userID = user.userID;
    log.deviceID = kLastBindDevice;
    log.logType = type;
    log.logDate = [NSString stringFromDate:[NSDate date]];
    
    [[DBManage sharedManager] insertData:log andTable:kLogTable];
}

// 警告音
- (void)playAudio {
    
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"message" ofType:@"mp3"];
    SystemSoundID sound;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath:soundPath]), &sound);
    AudioServicesPlaySystemSound(sound);
}

- (void)removePickerView
{
    [UIView animateWithDuration:0.5 animations:^{
        UIPickerView *pickerView = (UIPickerView *)[self.bgCtl viewWithTag:1000];
        pickerView.center = CGPointMake(kScreenWidth/2, kScreenHeight + 120/2);
    } completion:^(BOOL finished) {
        for (UIView *subView in self.bgCtl.subviews) {
            [subView removeFromSuperview];
        }
        if (self.bgCtl) {
            [self.bgCtl removeFromSuperview];
            self.bgCtl = nil;
        }
    }];
}

- (void)editAlertViewTapped
{
    if (self.bgCtl) {
        [self removePickerView];
    }
    
    self.bgCtl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.bgCtl addTarget:self action:@selector(removePickerView) forControlEvents:UIControlEventTouchUpInside ];
    self.bgCtl.backgroundColor = [UIColor clearColor];
    [self.backBtn addSubview:self.bgCtl];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 180)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.tag = 1000;
    [self.bgCtl addSubview:bgView];
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    UIBarButtonItem *cancelBarBtn = [[UIBarButtonItem alloc] initWithTitle:kLocal(@"cancel") style:UIBarButtonItemStyleBordered target:self action:@selector(cancelBarBtnClicked)];
    UIBarButtonItem *spaceBarBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *confirmBarBtn = [[UIBarButtonItem alloc] initWithTitle:kLocal(@"sure") style:UIBarButtonItemStyleBordered target:self action:@selector(confirmBarBtnClicked)];
    toolbar.items = @[cancelBarBtn, spaceBarBtn, confirmBarBtn];
    [bgView addSubview:toolbar];
    
    UIPickerView *numberPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, 140)];
    numberPicker.delegate = self;
    numberPicker.dataSource = self;
    numberPicker.tag = 2000;
    [bgView addSubview:numberPicker];
    
    [UIView animateWithDuration:0.5 animations:^{
        bgView.center = CGPointMake(kScreenWidth/2, kScreenHeight-160/2-64+5);
    }];
}

- (void)cancelBarBtnClicked
{
    [self removePickerView];
}

- (void)confirmBarBtnClicked
{
    UIPickerView *picker = (UIPickerView *)[[self.bgCtl viewWithTag:1000] viewWithTag:2000];
    self.shouldShowAlertMessageTemperatureValue = ([picker selectedRowInComponent:0] + 35) + ([picker selectedRowInComponent:2]/10.0f);
    NSString *alertStr = [NSString stringWithFormat:@"%@ %.1f℃, %@",kLocal(@"above_tem"),self.shouldShowAlertMessageTemperatureValue,kLocal(@"remind_me")];
    
    [[NSUserDefaults standardUserDefaults] setFloat:self.shouldShowAlertMessageTemperatureValue
                                             forKey:@"ShouldShowAlertMessageTemperatureValue"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:alertStr];
    NSRange location = [alertStr rangeOfString:[NSString stringWithFormat:@"%.1f℃",self.shouldShowAlertMessageTemperatureValue]];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[[UIColor blackColor] colorWithAlphaComponent:0.8]
                          range:NSMakeRange(0, location.location)];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[UIColor colorWithRed:62/255.0 green:180/255.0 blue:234/255.0 alpha:1.0]
                          range:NSMakeRange(location.location, location.length)];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[[UIColor blackColor] colorWithAlphaComponent:0.8]
                          range:NSMakeRange(location.location+location.length, attributedStr.length-(location.location+location.length))];
    self.label1.attributedText = attributedStr;
    
    [self removePickerView];
}

//- (void)scan
//{
//    [self.manager scanForPeripheralsWithServices:nil
//                                         options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
//}

//手势
- (void)handlePanGesture:(UIPanGestureRecognizer *)recognizer
{
    // if you have left and right sidebar, you can control the pan gesture by start point.
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint startPoint = [recognizer locationInView:self.view];
        
        // Left SideBar
        if (startPoint.x < 50) {
            _leftU.isCurrentPanGestureTarget = YES;
        }
        else if (startPoint.x > self.view.bounds.size.width-50){
            _rightB.isCurrentPanGestureTarget = YES;
        }
        // Right SideBar
        else {
//            _rightB.isCurrentPanGestureTarget = YES;
        }
    }
    [_leftU handlePanGestureToShow:recognizer inView:self.topDataView];
    [_rightB handlePanGestureToShow:recognizer inView:self.topDataView];
}


#pragma mark - UIPickerViewDataSource && Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 4;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return 7;
    }
    else if (component == 1 || component == 3) {
        return 1;
    }
    else if (component == 2) {
        return 10;
    }
    else {
        return 0;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == 1 || component == 2) {
        return 15;
    }
    else if (component == 0 || component == 3) {
        return 30;
    }
    else {
        return 0;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (component == 1 || component == 2) {
        UILabel *label = (UILabel *)view;
        if (!label) {
            label                 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
            label.backgroundColor = [UIColor whiteColor];
            label.textColor       = [UIColor darkGrayColor];
            label.textAlignment   = NSTextAlignmentCenter;
            label.font            = [UIFont systemFontOfSize:30];
        }
        if (component == 1) {
            label.text = @".";
        }
        else if (component == 2) {
            label.text = [NSString stringWithFormat:@"%ld",(long)row];
        }
        return label;
    }
    else if (component == 3 || component == 0) {
        UILabel *label = (UILabel *)view;
        if (!label) {
            label                 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 40)];
            label.backgroundColor = [UIColor whiteColor];
            label.textColor       = [UIColor darkGrayColor];
            label.font            = [UIFont systemFontOfSize:25];
        }
        if (component == 0) {
            label.textAlignment = NSTextAlignmentRight;
            label.text = [NSString stringWithFormat:@"%d",(int)row+35];
        }
        else if (component == 3) {
            label.textAlignment = NSTextAlignmentLeft;
            label.text = @"℃";
        }
        return label;
    }
    return nil;
}

#pragma mark - TouchBegan方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint startPoint = [[touches anyObject] locationInView:self.view];
    if (startPoint.x < 50) {
        _leftU.isCurrentPanGestureTarget = YES;
    }
    else if (startPoint.x > self.view.bounds.size.width-50){
        _rightB.isCurrentPanGestureTarget = YES;
    }
    // Right SideBar
    else {
        
    }
    [super touchesBegan:touches withEvent:event];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
